<style>
    .companyFormPhotos {
        /* margin-left:140px; */
        line-height: 38px;
        float: left;
    }

    .companyFormPhotos img {
        cursor: pointer;
        height: 38px;
        width: auto;
        max-width: 200px;
    }

    #warehouseOrderForm .layui-form-label {
        width: 130px;
    }

    #warehouseOrderForm .layui-input-block {
        margin-left: 140px;
    }
    #warehouseSignOrderFormContent .layui-form-label {
        width: 100px;
    }
    #warehouseSignOrderFormContent .layui-input-block {
        margin-left: 140px;
    }

    #signC .layui-table-cell {
        overflow: visible;
    }

    #signC .layui-table-box {
        overflow: visible !important;
    }

    #signC .layui-table-body {
        overflow: visible !important;
    }
    #SignFormContent .layui-table td, .layui-table th{
        padding: 9px 6px;
    }
    #signC .layui-table td, #signC .layui-table th{
        padding: 10px 0;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">所属客户</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="customerName" class="layui-input" type="text"
                                               placeholder="请输入所属客户" autocomplete="off"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">签收记录编号</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="signOrder" class="layui-input" type="text"
                                               placeholder="请输入签收记录编号" autocomplete="off"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">客户代码</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="customerId" class="layui-input" type="text"
                                               placeholder="请输入客户代码" autocomplete="off"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog"
                                            lay-submit layui-form-keyDownSearch="true">查询
                                    </button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置
                                    </button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="warehouseSignOrderBtnAdd" class="layui-btn icon-btn color-reseda">添加
                            </button>
                        </div>
                        <div class="lay-btn-rt">
                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="warehouseSignOrderTable"
                   lay-filter="warehouseSignOrderTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="warehouseSignOrderTableBar">
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="info">详情</a>
<!--    {{# if(d.status !== '5'){ }}-->
<!--    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="info">复核</a>-->
<!--    {{# } }}-->
    <!--    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>-->
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="warehouseSignOrderForm">
    <form lay-filter="warehouseSignOrderForm" id="warehouseSignOrderFormContent" class="layui-form model-form">
        <div class="open-auto">
            <div class="layui-form-item layui-row">
                <div class="layui-col-xs4">
                    <label class="layui-form-label ">选择发货单号</label>
                    <div class="layui-input-block">
                        <select  id="shipmentOrderCode" name="shipmentOrderCode" lay-filter="shipmentOrderCode" lay-verify="required" lay-search required>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-form-item tableContent">
                <table class="layui-table" id="shipmentOrderInfoTable"
                       lay-filter="shipmentOrderInfoTable"></table>
            </div>
            <div class="layui-form-item layui-row">
                <div class="layui-col-xs4">
                    <label class="layui-form-label">发货物料信息</label>
                    <div class="layui-form-item tableContent">
                        <table class="layui-table" id="shipmentOrderInfoDetailTable"
                               lay-filter="shipmentOrderInfoDetailTable"></table>
                    </div>
                </div>
                <div class="layui-col-xs6" style="margin-left: 50px">
                    <label class="layui-form-label">发货物料明细</label>
                    <div class="layui-form-item tableContent">
                        <table class="layui-table" id="inventoryTable"
                               lay-filter="inventoryTable"></table>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="warehouseSignOrderFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>
<script type="text/html" id="warehouseProductFormTableBar">
    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" type="button">删除</button>
    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="addDetail" type="button">添加明细</button>
</script>
<script type="text/html" id="shipmentOrderInfoDetailTableBar">
    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="select" type="button">选择</button>
</script>
<script type="text/html" id="inventoryTableBar">
    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" type="button">删除</button>
</script>
<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'upload', 'tableTreeDj', 'config', 'laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var tableTree = layui.tableTreeDj;
        var laydate = layui.laydate;
        var nowdata='';


        // 渲染表格
        var insTb = table.render({
            elem: '#warehouseSignOrderTable',
            url: config.base + 'warehouse/warehouse/signOrder/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers', title: '序号', fixed: 'left'}
                , {field: 'shipmentOrderCode', title: '签收记录编号', align: 'center'}
                , {field: 'waybill', title: '所属运单号', align: 'center'}
                , {field: 'orderCode', title: '关联合同', align: 'center'}
                , {field: 'totalQuantity', title: '签收数量', align: 'center'}
                , {field: 'customerId', title: '客户代码', align: 'center'}
                , {field: 'totalNetWeight', title: '总净重', align: 'center'}
                , {field: 'totalGrossWeight', title: '总毛重', align: 'center'}
                , {field: 'priceTime', title: '签收计价时间', align: 'center'}
                // , {field: 'orderStatus', title: '状态', align: 'center'}
                , {field: 'status', title: '状态', align: 'center',
                    templet: function (d) {
                        // 根据 status 的值返回对应的显示内容 0已撤销1.待受理2.已受理3.待发货4.已发货5.签收完成6.入库完成
                        switch (d.status) {
                            case '0':
                                return '<span>待受理</span>'; // 灰色
                            case "1":
                                return '<span>已受理</span>'; // 灰色
                            case "2":
                                return '<span>发货中</span>'; // 绿色
                            case "3":
                                return '<span>入库完成</span>';
                            case "4":
                                return '<span>已签收</span>';
                            case "5":
                                return '<span>已复核</span>';
                            default:
                                return "未知状态";
                        }
                    },
                }
                , {field: 'createTime', title: '创建时间', align: 'center'}
                , {field: 'creatorName', title: '创建人', align: 'center'}
                , {
                    align: 'center',
                    toolbar: '#warehouseSignOrderTableBar',
                    title: '操作',
                    width: 200,
                    fixed: 'right'
                }
            ]],
            done: function (res, curr, count) {
                //移除按钮
                // var menuButton = config.getMenuButton(location.hash);
                // if(menuButton.indexOf("搜索") == -1){
                //     $('.layui-form.toolbar').remove();
                // }
                // if(menuButton.indexOf("修改") == -1){
                //     $("[lay-event='edit']").remove();
                // }
                // if(menuButton.indexOf("删除") == -1){
                //     $("[lay-event='del']").remove();
                // }
            }
        });

        // 工具条点击事件
        table.on('tool(warehouseSignOrderTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'info') { //修改

                // data.shipmentOrderCode = data.shipmentOrderId;
                nowdata='info';
                admin.req(
                    "warehouse/warehouse/signOrder/Info",
                    {id: data.id},
                    (res) => {
                        if (res.code === 200) {
                            res.data.orderInfoDetail.map(i=>i.status=data.status)
                            showFormModel(res.data)
                        }
                    }
                );
                // showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            }
        });

        //监听排序
        table.on('sort(warehouseSignOrderTable)', function (obj) {
            table.reload('warehouseSignOrderTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            insTb.reload({where: admin.resetSearch(data.field), page: {curr: 1}}, 'data');
        });

        // 添加按钮点击事件
        $('#warehouseSignOrderBtnAdd').click(function () {
            nowdata='add';
            // showEditModel();
            showFormModel()
        });

        /*5.09修改添加及详情*/
        function showFormModel(data){
            admin.formOpen({
                area: ["90%", "90%"],
                offset: ["7%", "7%"],
                title: data ? "签收订单详情" : '添加签收记录',
                path: "components/warehouse/product/signOrderForm.html",
                success: function () {
                    if(data){
                        data.type='托管合同'
                        parentData.eventName='detail'
                        parentData.data=data
                    }
                }
            })
        }


        // 显示编辑弹窗///5.09修改前版本
        function showEditModel(data) {
            admin.formOpen({
                type: 1,
                area: ['90%', '95%'],
                offset: '35px',
                title: data ? '修改签收记录' : '添加签收记录',
                content: $('#warehouseSignOrderForm').html(),
                success: function () {
                    admin.reqSync('warehouse/warehouse/shipmentOrder/list?status=1', {"limit":9999}, function (res) {
                        layer.closeAll('loading');
                        if (res.code == 200) {
                            loadSelectHtml(res.data, "请选择发货订单", "shipmentOrderCode" , 1);
                        }
                    }, 'GET');
                    form.on('select(shipmentOrderCode)', function (data) {


                        if (data.value === '') {
                        } else {
                            let dataObj = JSON.parse($(data.elem[data.elem.selectedIndex]).attr('data'));

                            admin.reqSync('warehouse/warehouse/shipmentOrder/getInfoByShipmentId', {"shipmentOrderId":data.value}, function (res) {
                                layer.closeAll('loading');
                                if (res.code == 200) {
                                    table.reload('shipmentOrderInfoTable',{data:[res.data]});
                                    table.reload('shipmentOrderInfoDetailTable',{data:res.data.shipmentOrderDetailInfoList});
                                    table.reload('inventoryTable');
                                }
                            }, 'GET');

                        }
                    });

                    // 头部 发货记录信息
                    table.render({
                        elem: '#shipmentOrderInfoTable',
                        page: false,
                        limit: 999999,
                        height: 300,
                        data: [],
                        cols: [[
                            {field: 'shipmentOrderCode', title: '发货记录编号', align: 'center'}
                            , {field: 'sourceDesc', title: '数据来源', align: 'center'}
                            , {field: 'orderCode', title: '所属托管订单编号', align: 'center'}
                            , {field: 'customerId', title: '客户代码', align: 'center'}
                            , {field: 'netWeight', title: '物料净重', align: 'center'}
                            , {field: 'grossWeight', title: '物料毛重', align: 'center'}
                            , {field: 'waybill', title: '运单号', align: 'center'}
                            , {field: 'plateNo', title: '车牌号', align: 'center'}
                            , {field: 'driverName', title: '司机', align: 'center'}
                            , {field: 'driverPhone', title: '司机电话', align: 'center'}
                            , {field: 'shipmentOrderStatusDesc', title: '状态', align: 'center'}
                            , {field: 'createTime', title: '签收时间', align: 'center'}
                            , {field: 'creator', title: '签收人', align: 'center'}
                        ]],
                        done: function () {
                        },
                    });
                    // 左侧 发货物料信息
                    table.render({
                        elem: '#shipmentOrderInfoDetailTable',
                        page: false,
                        limit: 999999,
                        height: 240,
                        data: [],
                        cols: [[
                            {field: 'productCode', title: '客户物料料号', align: 'center'}
                            , {field: 'productMaterial', title: '物料类别', align: 'center'}
                            , {field: 'productProducer', title: '生产厂家', align: 'center'}
                            , {field: 'productBrand', title: '品牌', align: 'center'}
                            , {field: 'productMainUnit', title: '单位', align: 'center'}
                            , {field: 'totalQuantity', title: '发货数量', align: 'center'}
                            , {field: 'totalQuantity', title: '签收数量', align: 'center'}
                            , {
                                align: 'center',
                                toolbar: '#shipmentOrderInfoDetailTableBar',
                                title: '操作',
                                width: 100,
                                fixed: 'right',
                                hide: nowdata === 'info'
                            }
                        ]],
                        done: function () {

                        },
                    });
                    // debugger;
                    //如果是详情点击进来 就隐藏掉选择按钮
                    if(data){
                        // $('button[lay-event="select"]').hide();
                    }
                    // $('button[lay-event="select"]').addClass('layui-hide');

                    // 右侧 发货物料明细
                    table.render({
                        elem: '#inventoryTable',
                        page: false,
                        limit: 999999,
                        data: [],
                        height: 240,
                        cols: [[
                            {field: 'userBundleCode', title: '客户捆包号', align: 'center'}
                            , {field: 'sysBundleCode', title: '客户唯一码', align: 'center'}
                            , {field: 'netWeight', title: '单位净重(吨)', align: 'center'}
                            , {field: 'grossWeight', title: '单位毛重(吨)', align: 'center'}
                            , {
                                align: 'center',
                                toolbar: '#inventoryTableBar',
                                title: '操作',
                                width: 100,
                                fixed: 'right',
                                hide:data
                            }
                        ]],

                        done: function () {
                        },
                    });
                    if(data){

                        admin.reqSync('warehouse/warehouse/shipmentOrder/getInfoByShipmentId', {"shipmentOrderId":data.shipmentOrderId}, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {

                                table.reload('shipmentOrderInfoTable',{data:[res.data]});
                                table.reload('shipmentOrderInfoDetailTable',{data:res.data.shipmentOrderDetailInfoList});
                                const data = { /* 你的 JSON 数据 */ };

                                // 提取所有 shipmentProductInventoryList 并合并成一个数组
                                const allInventoryItems = res.data.shipmentOrderDetailInfoList.flatMap(
                                    item => item.shipmentProductInventoryList
                                );

                                console.log(allInventoryItems);
                                // 提取 `shipmentProductInventoryList`，筛选 `warehouseSignOrderId` 不等于特定值的
                                // const inventoryList = res.data.shipmentOrderDetailInfoList.flatMap(detail =>
                                //     detail.shipmentProductInventoryList
                                //         .filter(inventory => inventory.warehouseSignOrderId === data.id) // 过滤不等于某个值
                                //         .map(inventory => ({
                                //             inventoryId: inventory.id,
                                //             warehouseShipmentOrderId: inventory.warehouseShipmentOrderId,
                                //             warehouseSignOrderId: inventory.warehouseSignOrderId,
                                //             warehouseProductId: inventory.warehouseProductId,
                                //             userBundleCode: inventory.userBundleCode,
                                //             sysBundleCode: inventory.sysBundleCode,
                                //             customerId: inventory.customerId,
                                //             productId: detail.productId,
                                //             productName: detail.productName,
                                //             productCode: detail.productCode,
                                //             productMaterial: detail.productMaterial,
                                //             productBrand: detail.productBrand,
                                //             customer: detail.customer,
                                //             netWeight: inventory.netWeight,
                                //             grossWeight: inventory.grossWeight
                                //         }))
                                // );


                                // 重新加载 inventoryTable
                                table.reload('inventoryTable', {data: allInventoryItems});
                            }
                        }, 'GET');
                    }
                    form.val('warehouseSignOrderForm', data);

                    // 表单提交事件
                    form.on('submit(warehouseSignOrderFormSubmit)', function (d) {

                        const formData = table.cache['shipmentOrderInfoTable'][0];
                        // delete formData.id;
                        formData.warehouseSignOrderDetail = table.cache['shipmentOrderInfoDetailTable'];
                        formData.warehouseSignInventory = table.cache['inventoryTable'];
                        formData.totalQuantity = formData.warehouseSignInventory.length;

                        formData.shipmentOrderId=formData.id;

                        layer.load(2);
                        admin.req(data ? 'warehouse/warehouse/signOrder/update' : 'warehouse/warehouse/signOrder/add', JSON.stringify(formData), function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                layer.closeAll('page');
                                table.reload('warehouseSignOrderTable');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST', false, "application/json");
                        return false;
                    });
                    table.on('tool(shipmentOrderInfoDetailTable)', function (obj) {
                        var d = obj.data;  // 获取当前行的数据
                        var layEvent = obj.event;  // 获取事件名（edit 或 del）
                        if (obj.tr) {
                            obj.tr.on('click', function (e) {
                                e.preventDefault(); // 防止默认行为
                            });
                        }
                        if (layEvent == 'select') {
                            const oldData = table.cache['inventoryTable'];
                            const list = [...oldData, ...d.shipmentProductInventoryList];
                            // 使用 Map 以 `id` 作为 key 进行去重
                            const uniqueList = Array.from(new Map(list.map(item => [item.id, item])).values());
                            table.reload('inventoryTable', { data: uniqueList });
                        }
                    });
                    table.on('tool(inventoryTable)', function (obj) {
                        var d = obj.data;  // 获取当前行的数据
                        var layEvent = obj.event;  // 获取事件名（edit 或 del）
                        if (obj.tr) {
                            obj.tr.on('click', function (e) {
                                e.preventDefault(); // 防止默认行为
                            });
                        }
                        if (layEvent == 'del') {
                            const index = $(obj.tr[0]).data('index')
                            let list = table.cache['inventoryTable'].filter(v => {
                                return v['LAY_TABLE_INDEX'] != index
                            })
                            table.reload('inventoryTable', {
                                data: list
                            })
                        }
                    });
                }
            });
        }


        // option渲染
        function loadSelectHtml(data, tips, htmltarget, type) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type == 1) {
                    html += `<option value='${data[i].id}' id='${data[i].id}' data='${JSON.stringify(data[i])}' >${data[i].shipmentOrderCode}</option>`;
                } else if (type == 2) {
                    html += `<option value='${data[i].id}' id='${data[i].id}' data='${JSON.stringify(data[i])}'>${data[i].orderCode}</option>`;
                } else if (type == 3) {
                    html += `<option value='${data[i].id}' id='${data[i].id}' data='${JSON.stringify(data[i])}'>${data[i].labelName}</option>`;
                } else {
                    html += `<option value='${data[i].id}' data='${JSON.stringify(data[i])}'>${data[i].name}</option>`;
                }
            }

            $("form select[name='" + htmltarget + "']").html(html);
            form.render('select');
        }

        // 上传图片
        function uploadImg(_elem, pathId, inputId) {
            upload.render({
                elem: '#' + _elem
                , url: config.upload_url + 'uploadFile'
                , data: {}
                , accept: 'file'
                , exts: 'jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx'
                , headers: {Authorization: 'Bearer ' + config.getToken()}
                , done: function (res) {
                    if (res.code == 200) {
                        layer.msg(res.msg || "上传成功", {icon: 1});
                        let imagUrl = res.data.url;
                        $('#' + pathId).html('<img src="' + imagUrl + '"/>');
                        $('#' + inputId).val(imagUrl);
                    } else if (res.code == 502) {
                        return location.replace('member/login.html');
                    } else {
                        layer.msg(res.msg || "上传失败", {icon: 2});
                    }
                }
            });
        }
    });
</script>